const { observable, action } = require('mobx-miniprogram');
const documentRepository = require('../services/document_repository');
// 使用统一配置入口引用模型
const { DocumentModel } = require('../../config/models_config');

/**
 * 文档状态管理 Store
 * 使用MobX管理文档状态
 */
export const documentStore = observable({
  // 状态定义
  loading: false,
  error: null,
  documents: [],
  currentDocument: null,
  pagination: { page: 1, size: 20, total: 0 },
  filters: { fileType: 'all', tag: 'all', sortType: 'recent' },
  currentProjectId: '',
  uploadProgress: 0,
  
  /**
   * 获取项目文档列表
   * @param {String} projectId 项目ID
   * @param {Object} params 查询参数
   */
  async getProjectDocuments(projectId, params = {}) {
    if (!projectId) return;
    
    this.loading = true;
    this.error = null;
    this.currentProjectId = projectId;
    
    try {
      // 合并筛选参数
      const queryParams = { ...this.filters, ...params };
      
      // 调用仓储层
      const result = await documentRepository.getProjectDocuments(projectId, queryParams);
      
      // 批量更新状态
      this.documents = result.list || [];
      this.pagination = {
        page: result.page || 1,
        size: result.size || 20,
        total: result.total || 0
      };
      this.loading = false;
      
      return result;
    } catch (err) {
      this.error = err.message || '获取文档列表失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 获取文档详情
   * @param {String} id 文档ID
   */
  async getDocumentDetail(id) {
    if (!id) return;
    
    this.loading = true;
    this.error = null;
    
    try {
      // 调用仓储层
      const document = await documentRepository.getDocumentById(id);
      
      // 更新状态
      this.currentDocument = document;
      if (document && document.projectId) {
        this.currentProjectId = document.projectId;
      }
      this.loading = false;
      
      return document;
    } catch (err) {
      this.error = err.message || '获取文档详情失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 上传文档
   * @param {Object} documentData 文档数据
   * @param {String} tempFilePath 临时文件路径
   * @param {Function} progressCallback 进度回调
   */
  async uploadDocument(documentData, tempFilePath, progressCallback) {
    this.loading = true;
    this.error = null;
    this.uploadProgress = 0;
    
    try {
      // 确保设置了项目ID
      if (!documentData.projectId && this.currentProjectId) {
        documentData.projectId = this.currentProjectId;
      }
      
      // 转换为文档模型
      const document = new DocumentModel(documentData);
      
      // 设置上传进度回调
      if (progressCallback) {
        const originalCallback = progressCallback;
        progressCallback = (progress) => {
          this.uploadProgress = progress;
          originalCallback(progress);
        };
      } else {
        progressCallback = (progress) => {
          this.uploadProgress = progress;
        };
      }
      
      // 调用仓储层
      const result = await documentRepository.uploadDocument(document, tempFilePath, progressCallback);
      
      // 刷新列表
      if (this.currentProjectId) {
        await this.getProjectDocuments(this.currentProjectId);
      }
      
      this.loading = false;
      this.uploadProgress = 100;
      
      return result;
    } catch (err) {
      this.error = err.message || '上传文档失败';
      this.loading = false;
      this.uploadProgress = 0;
      throw err;
    }
  },
  
  /**
   * 更新文档信息
   * @param {Object} documentData 文档数据
   */
  async updateDocument(documentData) {
    if (!documentData._id) throw new Error('更新文档时ID不能为空');
    
    this.loading = true;
    this.error = null;
    
    try {
      // 转换为文档模型
      const document = new DocumentModel(documentData);
      
      // 调用仓储层
      const result = await documentRepository.updateDocument(document);
      
      // 更新当前文档
      if (this.currentDocument && this.currentDocument._id === document._id) {
        this.currentDocument = document;
      }
      
      // 刷新列表
      if (this.currentProjectId) {
        await this.getProjectDocuments(this.currentProjectId);
      }
      
      this.loading = false;
      
      return result;
    } catch (err) {
      this.error = err.message || '更新文档信息失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 删除文档
   * @param {String} id 文档ID
   * @param {String} fileId 文件ID
   */
  async deleteDocument(id, fileId) {
    if (!id) throw new Error('文档ID不能为空');
    if (!fileId) throw new Error('文件ID不能为空');
    
    this.loading = true;
    this.error = null;
    
    try {
      // 调用仓储层
      const result = await documentRepository.deleteDocument(id, fileId, this.currentProjectId);
      
      // 如果删除的是当前文档，重置当前文档
      if (this.currentDocument && this.currentDocument._id === id) {
        this.currentDocument = null;
      }
      
      // 刷新列表
      if (this.currentProjectId) {
        await this.getProjectDocuments(this.currentProjectId);
      }
      
      this.loading = false;
      
      return result;
    } catch (err) {
      this.error = err.message || '删除文档失败';
      this.loading = false;
      throw err;
    }
  },
  
  /**
   * 设置筛选条件
   * @param {Object} filters 筛选参数
   */
  setFilters: action(function(filters) {
    this.filters = { ...this.filters, ...filters };
    // 重置分页
    this.pagination.page = 1;
  }),
  
  /**
   * 重置当前文档
   */
  resetCurrentDocument: action(function() {
    this.currentDocument = null;
  }),
  
  /**
   * 设置当前项目ID
   */
  setCurrentProjectId: action(function(projectId) {
    this.currentProjectId = projectId;
  }),
  
  /**
   * 重置上传进度
   */
  resetUploadProgress: action(function() {
    this.uploadProgress = 0;
  })
}); 